package com.small.xx.ai.spring.structuredoutput.controller;

import com.small.xx.ai.spring.structuredoutput.BeanEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.converter.BeanOutputConverter;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * map、list、实例对象类型的格式化输出案例
 */
@RestController
@RequestMapping("/chat/bean")
public class BeanChatMessageController {

    private static final Logger log = LoggerFactory.getLogger(BeanChatMessageController.class);

    private final ChatClient chatClient;
    private final BeanOutputConverter<BeanEntity> converter;

    public BeanChatMessageController(ChatClient.Builder builder) {
        this.converter = new BeanOutputConverter<>(new ParameterizedTypeReference<BeanEntity>() {
        });
        this.chatClient = builder.build();
    }

    @GetMapping("/call")
    public String call(
        @RequestParam(value = "query", defaultValue = "以XX为作者，写一篇200字左右的有关人工智能诗篇") String query) {
        String result =
            chatClient.prompt(query)
                .options(OllamaOptions.builder().format(this.converter.getJsonSchemaMap()).build())
                .call().content();
        log.info("result: {}", result);
        System.out.println("BeanChatMessageController.call");
        System.out.println("query = " + query);
        System.out.println("result = " + result);
        assert result != null;
        try {
            BeanEntity convert = converter.convert(result);
            log.info("反序列成功，convert: {}", convert);
        } catch (Exception e) {
            log.error("反序列化失败");
        }
        return result;
    }

    @GetMapping("/call/format")
    public BeanEntity callFormat(
        @RequestParam(value = "query", defaultValue = "以XX为作者，写一篇200字左右的有关人工智能诗篇") String query) {
        return chatClient.prompt(query).call().entity(BeanEntity.class);
    }

}